package com.fla.millioner.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import net.londatiga.android.QuickAction.OnActionItemClickListener;

import com.alone1672.millioner.R;
import com.danikula.aibolit.Aibolit;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectView;
import com.fla.millioner.MillionerApplication;
import com.fla.millioner.MillionerApplication.OnFontSizeChangedListener;
import com.fla.millioner.Question;
import com.fla.millioner.QuestionService;
import com.fla.millioner.Utils;
import com.fla.millioner.ui.HelpUtils.AnswerModel;
import com.fla.millioner.ui.support.AndroidUtils;
import com.fla.millioner.ui.support.AnswerView;
import com.fla.millioner.ui.support.LevelsAdapter;
import com.fla.millioner.ui.support.ProgressedAsyncTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class GameActivity extends Activity {
    @InjectService
    private MillionerApplication millionerApplication;

    @InjectService
    private QuestionService questionService;

    @InjectView(R.id.questionTextView)
    private TextView questionTextView;

    @InjectView(R.id.vertialBanner)
    private View vertialBanner;

    @InjectView(R.id.horizontalBanner)
    private View horizontalBanner;

    @InjectView(R.id.answer1)
    private AnswerView answer1;

    @InjectView(R.id.answer2)
    private AnswerView answer2;

    @InjectView(R.id.answer3)
    private AnswerView answer3;

    @InjectView(R.id.answer4)
    private AnswerView answer4;

    @InjectView(R.id.luckyImage)
    private View luckyImage;

    @InjectView(R.id.listView)
    private ListView levelsListView;

    @InjectView(R.id.fiftyTextView)
    private TextView fiftyTextView;

    @InjectView(R.id.quoterTextView)
    private TextView quoterTextView;

    @InjectView(R.id.zalTextView)
    private TextView zalTextView;

    @InjectView(R.id.callTextView)
    private TextView callTextView;

    private AnswerView[] answerViews;

    private Handler handler;

    private QuickAction quickAction;

    private LevelsAdapter levelsAdapter;

    private AnswerView correctAnswerView;

    private int level = 0;

    private OnFontSizeChangedListener fontSizeChangedListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler();
        Aibolit.setInjectedContentView(this, R.layout.game_activity);

        updateBannerPosition(getResources().getConfiguration());

        levelsAdapter = new LevelsAdapter(this);
        levelsListView.setAdapter(levelsAdapter);

        answerViews = new AnswerView[] {answer1, answer2, answer3, answer4};

        for (AnswerView answerView : answerViews) {
            answerView.setOnClickListener(new AnswerClickHandler());
        }

        fontSizeChangedListener = new FontSizeChangedHandler();
        fontSizeChangedListener.onFontSizeChanged(millionerApplication.getCurrentFontSize());

        processCorrectAnswer();
    }

    @Override
    protected void onResume() {
        super.onResume();
        millionerApplication.addOnFontSizeChangedListener(fontSizeChangedListener);
    }

    @Override
    protected void onPause() {
        millionerApplication.removeOnFontSizeChangedListener(fontSizeChangedListener);
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        final int score = getScore(false);
        final String win = String.format("Забрать %s$ и выйти", score);

        showOkNoDialog("Выход", win + " ?", score);
    }

    private void bindQuestion(Question question) {
        questionTextView.setText(question.getQuestion());

        for (AnswerView answerView : answerViews) {
            answerView.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < 4; i++) {
            answerViews[i].setAnswer(question.getAnswers()[i]);
        }

        int random = (int) (Math.round(3 * Math.random()));
        // int random = 0;
        correctAnswerView = answerViews[random];
        correctAnswerView.setAnswer(question.getAnswers()[0]);
        answerViews[0].setAnswer(question.getAnswers()[random]);
    }

    private void processCorrectAnswer() {
        new AnswerProcessorTask(this).execute();
    }

    private void processWrongAnswer() {
        final int score = getScore(true);
        showOkDialog("Вы проиграли!", "Ваш выигрыш: " + score + " $", score);
    }

    private void updateBannerPosition(Configuration configuration) {
        boolean isHorizontal = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE;

        Utils.setVisibility(!isHorizontal, vertialBanner);
        Utils.setVisibility(!isHorizontal, luckyImage);
        Utils.setVisibility(isHorizontal, horizontalBanner);

//        WebView wv = isHorizontal ? (WebView) horizontalBanner : (WebView) vertialBanner;
//        wv.getSettings().setJavaScriptEnabled(true);
//        wv.setBackgroundColor(Color.TRANSPARENT);
//        String html = String.format(" <script type=\"text/javascript\" src=\"http://ad.leadboltads.net/show_app_ad.js?section_id=%s\"></script>", "574347126");
//        wv.loadData(html, "text/html", "utf-8");
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateBannerPosition(newConfig);
        if (quickAction != null) {
            quickAction.dismiss();
        }
    }

    private boolean isAllAnswersVisible() {
        for (AnswerView answerView : answerViews) {
            if (answerView.getVisibility() != View.VISIBLE) {
                return false;
            }
        }
        return true;
    }

    @InjectOnClickListener(R.id.questionTextView)
    private void onQuestionClicked(View view) {
//        processCorrectAnswer();
    }

    @InjectOnClickListener(R.id.fiftyTextView)
    private void onFiftyClicked(View view) {
        if (isAllAnswersVisible()) {
            fiftyTextView.setEnabled(false);
            fiftyTextView.setBackgroundResource(R.drawable.round_shape_done);
            fiftyTextView.setTextColor(Color.GRAY);

            List<AnswerView> answers = new ArrayList<AnswerView>(Arrays.asList(answerViews));
            answers.remove(correctAnswerView);
            Collections.shuffle(answers);
            answers.get(0).setVisibility(View.INVISIBLE);
            answers.get(1).setVisibility(View.INVISIBLE);
        }
    }

    @InjectOnClickListener(R.id.quoterTextView)
    private void onQuoterClicked(View view) {
        if (isAllAnswersVisible()) {
            quoterTextView.setEnabled(false);
            quoterTextView.setBackgroundResource(R.drawable.round_shape_done);
            quoterTextView.setTextColor(Color.GRAY);

            List<AnswerView> answers = new ArrayList<AnswerView>(Arrays.asList(answerViews));
            answers.remove(correctAnswerView);
            Collections.shuffle(answers);
            answers.get(0).setVisibility(View.INVISIBLE);
        }
    }

    @InjectOnClickListener(R.id.zalTextView)
    private void onZalClicked(View view) {
        zalTextView.setEnabled(false);
        zalTextView.setBackgroundResource(R.drawable.round_shape_done);
        zalTextView.setTextColor(Color.GRAY);

        AnswerModel[] answerModels = new AnswerModel[4];
        for (int i = 0; i < 4; i++) {
            AnswerView answerView = answerViews[i];
            answerModels[i] = new AnswerModel(answerView == correctAnswerView, answerView.getVisibility() == View.VISIBLE,
                answerView.getAnswer());
        }

        new ZalDialog(this, level, answerModels).show();
    }

    @InjectOnClickListener(R.id.callTextView)
    private void onCallClicked(View view) {
        callTextView.setEnabled(false);
        callTextView.setBackgroundResource(R.drawable.round_shape_done);
        callTextView.setTextColor(Color.GRAY);

        AnswerModel[] answerModels = new AnswerModel[4];
        for (int i = 0; i < 4; i++) {
            AnswerView answerView = answerViews[i];
            answerModels[i] = new AnswerModel(answerView == correctAnswerView, answerView.getVisibility() == View.VISIBLE,
                answerView.getAnswer());
        }

        new CallDialog(this, level, answerModels).show();
    }

    @InjectOnClickListener(R.id.infoButton)
    private void onToolsClicked(View view) {
        final int score = getScore(false);
        final String win = String.format("Забрать %s$ и выйти", score);

        String sountText = millionerApplication.isSoundEnabled() ? "Отключить звук" : "Включить звук";
        int soundId = millionerApplication.isSoundEnabled() ? R.drawable.sound : R.drawable.sound_disabled;

        quickAction = new QuickAction(this, QuickAction.VERTICAL);
        quickAction.addActionItem(new ActionItem(0, win, getResources().getDrawable(R.drawable.dollar)));
        if (!MillionerApplication.FOR_SAMSUNG) {
            quickAction.addActionItem(new ActionItem(1, sountText, getResources().getDrawable(soundId)));
        }
        quickAction.addActionItem(new ActionItem(2, "Изменить шрифт", getResources().getDrawable(R.drawable.font)));

        quickAction.setOnActionItemClickListener(new OnActionItemClickListener() {
            @Override
            public void onItemClick(QuickAction source, int pos, int actionId) {
                switch (actionId) {
                    case 0:
                        showOkNoDialog("Выход", win + " ?", score);
                        break;
                    case 1:
                        millionerApplication.setSoundEnabled(!millionerApplication.isSoundEnabled());
                        break;
                    case 2:
                        millionerApplication.showChangeFontSizeDialog(GameActivity.this);
                        break;
                }
            }
        });

        quickAction.show(view);
    }

    private void showOkNoDialog(String title, String text, final int score) {
        if (!isFinishing()) {
            Utils.showOkNoDialog(this, title, text, new Dialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveBestAndExit(score);
                }
            });
        }
    }

    private void showOkDialog(String title, String text, final int score) {
        Utils.showOkDialog(this, title, text, "Ok", new Dialog.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveBestAndExit(score);
            }
        });
    }

    private void saveBestAndExit(int score) {
        if (score > millionerApplication.getBestResult()) {
            millionerApplication.setBestResult(score);
        }
        finish();
    }

    private int getScore(boolean roundToUnbirn) {
        int currentLevel = !roundToUnbirn ? level - 1 : 5 * ((level - 1) / 5);
        return currentLevel > 0 ? MillionerApplication.LEVELS_DATA[15 - currentLevel] : 0;
    }

    private void disableButtons() {
        for (AnswerView answerView : answerViews) {
            answerView.setClickable(false);
        }
        fiftyTextView.setClickable(false);
        quoterTextView.setClickable(false);
        zalTextView.setClickable(false);
        callTextView.setClickable(false);
    }

    private void enableButtons() {
        for (AnswerView answerView : answerViews) {
            answerView.setClickable(true);
        }
        fiftyTextView.setClickable(true);
        quoterTextView.setClickable(true);
        zalTextView.setClickable(true);
        callTextView.setClickable(true);
    }

    private class AnswerClickHandler implements OnClickListener {
        @Override
        public void onClick(View v) {
            disableButtons();

            AnswerView answerView = (AnswerView) v;
            answerView.makeYellow();

            handler.postDelayed(new AnswerChecker(correctAnswerView, answerView), 1500);
        }
    }

    private class AnswerChecker implements Runnable {
        private final AnswerView correctAnswer;

        private final AnswerView choosenAnswer;

        public AnswerChecker(AnswerView correctAnswer, AnswerView choosenAnswer) {
            this.correctAnswer = correctAnswer;
            this.choosenAnswer = choosenAnswer;
        }

        @Override
        public void run() {
            if (correctAnswer == choosenAnswer) {
                playSoundIfEnabled(R.raw.answer_true);
                choosenAnswer.makeGreen();
                handler.postDelayed(new ProcessAnswer(true), 2000);
            }
            else {
                playSoundIfEnabled(R.raw.answer_false);
                choosenAnswer.makeRed();
                correctAnswer.makeGreen();
                handler.postDelayed(new ProcessAnswer(false), 2000);
            }
        }

        private void playSoundIfEnabled(int sound) {
            if (millionerApplication.isSoundEnabled()) {
                AndroidUtils.playSound(GameActivity.this, sound);
            }
        }
    }

    private class ProcessAnswer implements Runnable {
        private final boolean isCorrect;

        public ProcessAnswer(boolean isCorrect) {
            this.isCorrect = isCorrect;
        }

        @Override
        public void run() {
            if (!isFinishing()) {
                if (isCorrect) {
                    processCorrectAnswer();
                }
                else {
                    processWrongAnswer();
                }
            }
        }
    }

    private class FontSizeChangedHandler implements OnFontSizeChangedListener {
        @Override
        public void onFontSizeChanged(float newFontSize) {
            questionTextView.setTextSize(newFontSize);

            for (AnswerView answerView : answerViews) {
                answerView.setTextSize(newFontSize);
            }
        }
    }

    private class AnswerProcessorTask extends ProgressedAsyncTask<Void, Void, Question> {

        public AnswerProcessorTask(Context context) {
            super(context);
        }

        @Override
        protected void onBeforeExecute() {
            enableButtons();
            for (AnswerView answerView : answerViews) {
                answerView.makeDefault();
            }
            levelsAdapter.updateLevel(level);
        }

        @Override
        protected Question executeInBackground(Void... params) throws Exception {
            level++;
            return level <= 15 ? questionService.getQuestionMarkRead(level) : null;
        }

        @Override
        protected void onAfterExecute(Question result) {
            if (level <= 15) {
                bindQuestion(result);
            }
            else {
                final int score = getScore(false);
                showOkDialog("Победа!", "Поздравляем!!! Вы выиграли: " + score + " $", score);
            }
        }
    }
}
